package com.zrb.mobile;

import java.util.Date;

import org.apache.http.Header;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zrb.mobile.adapter.FindMoneyAdapter;
import com.zrb.mobile.adapter.model.FindMoneyDto;
import com.zrb.mobile.adapter.model.FindMoneyDtos;
import com.zrb.mobile.pulltorefresh.PullToRefreshBase;
import com.zrb.mobile.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.zrb.mobile.ui.EmptyView;
import com.zrb.mobile.ui.OnCityChoose;
import com.zrb.mobile.ui.PullToRefreshListViewEx;
import com.zrb.mobile.ui.onLoadMoreListener;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.Constants;
import com.zrb.mobile.utility.ZrbRestClient;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class FindMoney_MainFragment extends BaseLazyFragment implements
		onLoadMoreListener  {

	PullToRefreshListViewEx msearchResults;
	FindMoneyAdapter mAdapter2;
	int currentPage;
	Handler mhandler = new Handler();
	boolean isFirstIn = true;
	 
	int curIndustryCode=Constants.ALLIndustryCode;//全部行业
	int curPostcode=0;	
	EmptyView emptylayout;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		//registerBoradcastReceiver1();
		View view = inflater.inflate(R.layout.findmoney_mainfragment, container, false);
	 
		emptylayout=(EmptyView)view.findViewById(R.id.include_empty_layout);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		// mNewsItemDao = new NewsItemDao(getActivity());

		msearchResults = (PullToRefreshListViewEx) this.getView().findViewById(
				R.id.discover_list_view);
		msearchResults.setPagesize(10);
		// Set a listener to be invoked when the list should be refreshed.
		msearchResults.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {

				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(
						CommonUtil.getcurTime(getActivity()));
				currentPage = 1;
				mhandler.postDelayed(new Runnable() {
					@Override
					public void run() {
						LoadData(-1, true);
					}
				}, 1000);
			}
		});

		mAdapter2 = new FindMoneyAdapter(getActivity());
		msearchResults.initAdapter(mAdapter2);
		msearchResults.setOnLoadMoreListener(this);
		msearchResults.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				FindMoneyDto tmpDto = mAdapter2.CurrentDatas.get(arg2 - 1);
				Intent intent = new Intent(FindMoney_MainFragment.this
						.getActivity(), MoneyDetailActivity.class);
				intent.putExtra("id", tmpDto.id);
				intent.putExtra("title", tmpDto.title);
				intent.putExtra("position", arg2 - 1);
				intent.putExtra("from", "1");
				/*
				 * MemoryCache.getInstance().add(Constants.FindMoneytag, new
				 * FocusTmpDto(arg2 - 1, tmpDto.collectNum));
				 */

				startActivity(intent);
			}
		});
	}

	// 加载更多
	@Override
	public void OnLoadMoreEvent() {
		// TODO Auto-generated method stub
		currentPage++;
		mhandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				LoadData(mAdapter2.getMinTime(), false);
			}
		}, 400);
	}

	// 上拉加载更多 fund/list?pushTime=2015-09-24%2023:59:59&limit=10
	private void LoadData(long minTime, boolean isreflesh) {
		  String url = String.format("fund/searchList?limit=%1$s",10);// &tradeDates=%2$s
	 
	     if(minTime!=-1)                                    url+="&pushTime="+minTime;
	     if(curIndustryCode!=Constants.ALLIndustryCode)     url+="&industrys="+curIndustryCode;
	     if(curPostcode>0)                                  url+="&citys="+curPostcode;
	 
	     
	     
		ZrbRestClient.get(url, null, new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
			    CommonUtil.showToast(R.string.error_net_loadfail, FindMoney_MainFragment.this.getActivity());
				if (currentPage > 1)
					msearchResults.hideloading();
				else
					msearchResults.onRefreshComplete();
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				// loadingview.Hide();
				String results = new String(arg2);
				if (currentPage == 1) msearchResults.onRefreshComplete();
				else
					msearchResults.hideloading();
 				try {
					Gson gson = new Gson();
					FindMoneyDtos tmpDto = gson.fromJson(results, FindMoneyDtos.class);
					if (tmpDto.res == 1) {
						if (tmpDto.data != null && tmpDto.data.size() > 0) {
 							  emptylayout.checkhide() ;   
 							  mAdapter2.setDatas(tmpDto.data,currentPage>1);
							  mAdapter2.notifyDataSetChanged();
  						} else {
  							if(currentPage==1){
  								 mAdapter2.CurrentDatas.clear();
  							     mAdapter2.notifyDataSetChanged();
  							     emptylayout.show();
   							} 
  							else
  								CommonUtil.showToast("暂无更多信息~~",  getActivity());
						}
 					} else
						CommonUtil.showToast(tmpDto.msg, getActivity());
				} catch (Exception e) {
					CommonUtil.showToast( R.string.error_serverdata_loadfail ,
							FindMoney_MainFragment.this.getActivity());
				}
			}
		});
	}

	private void firstLoad() {
		if (isFirstIn) {
			isFirstIn = false;
			mhandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					msearchResults.setRefreshing(true);
				}
			}, 200);
		}
	}

	@Override
	public void onFirstUserVisible() {
		  firstLoad();
    }
 
	
	@Override
	public void onResume() {
		super.onResume();

		/*
		 * FocusTmpDto tmpobj = MemoryCache.getInstance().get(
		 * Constants.FindMoneytag);
		 */
		if (this.getUserVisibleHint())
			firstLoad();
	}

	 
 
	public void registerBoradcastReceiver1() {
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(Constants.FocusNum_MONEYDETIALS_mainlist);
		// 注册广播
		FindMoney_MainFragment.this.getActivity().registerReceiver(
				mBroadcastReceiver1, myIntentFilter);
	}

	private BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Constants.FocusNum_MONEYDETIALS_mainlist)) {
				String from = intent.getStringExtra("from");
				int position = intent.getIntExtra("position", -1);

				if ("1".equals(from)) {
					int attention = intent.getIntExtra("attention", -1);
					Log.i("from", from);
					Log.i("attention", attention + "");
					Log.i("position", position + "");
					if (attention != -1) {
						if (attention == 0) {
							// 取消关注
							CanFocus(position);
						} else {
							// 添加关注
							AddFocus(position);
						}
					}

				}
			}
		}
	};

	// 取消关注效果
	protected void CanFocus(int position) {
		// TODO Auto-generated method stub
		mAdapter2.CurrentDatas.get(position).collectNum = mAdapter2.CurrentDatas
				.get(position).collectNum - 1;
		Log.i("collectNum--", mAdapter2.CurrentDatas.get(position).collectNum
				+ "");
		mAdapter2.notifyDataSetChanged();
	}

	// 添加关注效果
	protected void AddFocus(int position) {
		// TODO Auto-generated method stub
		mAdapter2.CurrentDatas.get(position).collectNum = mAdapter2.CurrentDatas
				.get(position).collectNum + 1;
		Log.i("collectNum++", mAdapter2.CurrentDatas.get(position).collectNum
				+ "");
		mAdapter2.notifyDataSetChanged();
	}

	/*
	 * 
	 * 
	 * 广播接收者的注册和接收
	 */
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// 销毁广播
	/*	FindMoney_MainFragment.this.getActivity().unregisterReceiver(
				mBroadcastReceiver1);*/
	}

}